package com.party.web.web.security;

import com.alibaba.fastjson.JSONObject;
import com.party.web.biz.user.LoginBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.AjaxResult;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @ClassName MyFormAuthenticationFilter
 * @Description 自定义表单拦截器
 * @Author yifeng
 * @Date 2019/1/28 11:16
 **/
@Component
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
    @Autowired
    private LoginBizService loginBizService;

    @Override
    protected AuthenticationToken createToken(String username, String password, ServletRequest request, ServletResponse response) {
        boolean rememberMe = isRememberMe(request);
        String host = getHost(request);
        return new MyUsernamePasswordToken(username, password, LoginType.NOPASSWD.getCode(), rememberMe, host);
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        CurrentUser newCurrentUser = RealmUtils.getNewCurrentUser();
        MyUsernamePasswordToken myUsernamePasswordToken = null;
        if (token instanceof MyUsernamePasswordToken) {
            myUsernamePasswordToken = (MyUsernamePasswordToken) token;
        }

        AjaxResult ajaxResult = loginBizService.getForwardUrl(myUsernamePasswordToken, subject, newCurrentUser);

//        WebUtils.issueRedirect(request, response, redirectUrl);

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setCharacterEncoding("UTF-8");
        PrintWriter out = httpServletResponse.getWriter();

        out.println(JSONObject.toJSONString(ajaxResult));
        out.flush();
        out.close();
        return false;
    }
}
